// Copyright (c) Microsoft Corporation.  All rights reserved.

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Runtime.InteropServices;

namespace SSISAccess
{
    class Firewall
    {
        private object remoteAdminSettings;

        public Firewall() { }

        public UInt32 Initialize() {
            UInt32 retVal = 0;

            try
            {
                // Get the firewall API
                Type firewallManagerType = Type.GetTypeFromProgID("HNetCfg.FwMgr");
                object firewallManager = Activator.CreateInstance(firewallManagerType);

                // Get the remote administration settings object
                object localPolicy = firewallManagerType.InvokeMember("LocalPolicy", BindingFlags.GetProperty, null, firewallManager, null);
                object profile = localPolicy.GetType().InvokeMember("CurrentProfile", BindingFlags.GetProperty, null, localPolicy, null);
                this.remoteAdminSettings = profile.GetType().InvokeMember("RemoteAdminSettings", BindingFlags.GetProperty, null, profile, null);
            }
            catch (TargetInvocationException ex)
            {
                COMException comEx = ex.InnerException as COMException;
                if (comEx != null)
                {
                    retVal = (uint)comEx.ErrorCode;
                }
                else
                {
                    // return an EFAIL
                    retVal = 0x80004005;
                }
            }
            catch (COMException ex)
            {
                retVal = (uint)ex.ErrorCode;
            }

            return retVal;
        }

        public void EnableRemoteAdministration(bool enable) {
            this.remoteAdminSettings.GetType().InvokeMember("Enabled", BindingFlags.SetProperty,
                null, this.remoteAdminSettings, new object[] { enable });
        }

        public bool IsRemoteAdministrationEnabled()
        {
            return (bool)this.remoteAdminSettings.GetType().InvokeMember("Enabled", BindingFlags.GetProperty,
                null, this.remoteAdminSettings, null);
        }
    }
}
